package com.simple.crawler.utils;

import java.io.*;

public class IOUtils {

    public static ByteArrayOutputStream read(InputStream in, ByteArrayOutputStream out) throws Exception {
        byte[] buf = new byte[1024];
        while (true) {
            int len = in.read(buf);
            if (len == -1) {
                break;
            }
            out.write(buf, 0, len);
        }
        in.close();
        return out;
    }

    public static StringBuilder read(InputStream in, StringBuilder out) {
        return read(in, "UTF-8", out);
    }

    public static StringBuilder read(InputStream in, String charSet, StringBuilder out) {
        try {
            InputStreamReader isr = new InputStreamReader(in, charSet);
            BufferedReader bfr = new BufferedReader(isr);
            while (true) {
                String line = bfr.readLine();
                if (StringUtils.isNull(line)) {
                    break;
                }
                out.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out;
    }

    public static boolean download(InputStream in, String dir, String fileName) {
        try {
            FileOutputStream fos = new FileOutputStream(dir + fileName);
            byte[] buffer = new byte[1024];
            while (true) {
                int len = in.read(buffer);
                if (len == -1) {
                    break;
                }
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

}
